package com.gulangyu.trade.mvc;

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
import com.gulangyu.trade.ws.NeedLogin;
import com.mycompany.yourtrade.common.DerongVariables;
import com.mycompany.yourtrade.common.RedisService;
import com.mycompany.yourtrade.common.UpYunService;
import com.mycompany.yourtrade.enums.OrderState;
import com.mycompany.yourtrade.model.AjaxResponse;
import com.mycompany.yourtrade.model.Area;
import com.mycompany.yourtrade.model.Category;
import com.mycompany.yourtrade.model.City;
import com.mycompany.yourtrade.model.Commodity;
import com.mycompany.yourtrade.model.Cooperation;
import com.mycompany.yourtrade.model.LoginUser;
import com.mycompany.yourtrade.model.Order;
import com.mycompany.yourtrade.model.OrderDto;
import com.mycompany.yourtrade.model.Province;
import com.mycompany.yourtrade.model.Shop;
import com.mycompany.yourtrade.model.Streets;
import com.mycompany.yourtrade.model.UserAddress;
import com.mycompany.yourtrade.model.UserBean;
import com.mycompany.yourtrade.model.UserCart;
import com.mycompany.yourtrade.model.UserStore;
import com.mycompany.yourtrade.service.manage.ShopManageService;
import com.mycompany.yourtrade.service.user.UserOrderService;
import com.mycompany.yourtrade.service.user.UserService;
import com.qunshang.common.SessionUtils;
import com.qunshang.common.UserBeanSession;
import java.awt.Color;
import java.awt.Font;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import nl.captcha.Captcha;
import nl.captcha.text.producer.DefaultTextProducer;
import nl.captcha.text.renderer.DefaultWordRenderer;
import org.apache.commons.lang3.StringUtils;
import org.mindrot.jbcrypt.BCrypt;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/")
public class HomeController {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private UpYunService UpYunService;
    @Autowired
    private UserService userService;
    @Autowired
    private UserOrderService userOrderService;
    @Autowired
    private RedisService redisService;
    @Autowired
    private DerongVariables derongVariables;
    @Autowired
    private ShopManageService shopManageService;

    @RequestMapping(value = "login", method = RequestMethod.GET)
    public ModelAndView login(ModelMap model) {
        ModelAndView mv = new ModelAndView("login");
        return mv;
    }

    /**
     * 验证登录
     *
     * @param request
     * @param response
     * @param model
     * @param result
     * @param imageCaptcha
     * @return
     */
    @RequestMapping(value = "checklogin", method = RequestMethod.POST)
    public @ResponseBody
    AjaxResponse userlogin(HttpServletRequest request, HttpServletResponse response,
            @Valid LoginUser model,
            BindingResult result,
            String imageCaptcha) {
        try {
            if (!SessionUtils.validateCaptcha(request, imageCaptcha)) {
                return new AjaxResponse(false, "图片验证码不正确");
            }
            if (!result.hasErrors()) {
                UserBean userBean = userService.getUserBeanByMobile(model.getMobile());
                if (userBean != null) {
                    if (BCrypt.checkpw(model.getPassword(), userBean.getPassword())) {
                        // 创建用户Session
                        UserBeanSession session = new UserBeanSession(userBean);
                        SessionUtils.setSession(request, session);
                        return new AjaxResponse(true);
                    } else {
                        return new AjaxResponse(false, "密码错误");
                    }
                } else {
                    return new AjaxResponse(false, "不存在该用户，请先注册");
                }
            }
        } catch (Exception e) {
            logger.error(e.toString());
        }
        return new AjaxResponse(false, "系统错误");
    }

    /**
     * 快速登录
     *
     * @param request
     * @param response
     * @param mobile
     * @param imageCaptcha
     * @param checkcode
     * @return
     */
    @RequestMapping(value = "quicklogin", method = RequestMethod.POST)
    public @ResponseBody
    AjaxResponse quicklogin(HttpServletRequest request, HttpServletResponse response, String mobile,
            String imageCaptcha, String checkcode) {
        try {
            if (!SessionUtils.validateCaptcha(request, imageCaptcha)) {
                return new AjaxResponse(false, "图片验证码不正确");
            }
            String sessionId = request.getSession().getId();
            String redis = redisService.getValueOps().get(sessionId);
            if (redis == null) {
                return new AjaxResponse(false, "手机验证码已失效，请重新发送验证码");
            } else {
                if (!checkcode.equals(redis)) {
                    return new AjaxResponse(false, "手机验证码不正确");
                } else {
                    UserBean userBean = userService.getUserBeanByMobile(mobile);
                    if (userBean != null) {
                        // 创建用户Session
                        UserBeanSession session = new UserBeanSession(userBean);
                        SessionUtils.setSession(request, session);
                        return new AjaxResponse(true);
                    } else {
                        return new AjaxResponse(false, "不存在该用户，请先注册");
                    }
                }
            }

        } catch (Exception e) {
            logger.error(e.toString());
        }
        return new AjaxResponse(false, "系统错误");
    }

    /**
     * 更改密码---根据旧密码更改新密码
     *
     * @param request
     * @param response
     * @param model
     * @param result
     * @param newpwd
     * @return
     */
    @NeedLogin
    @RequestMapping(value = "updatePwd", method = RequestMethod.POST)
    public @ResponseBody
    AjaxResponse updatePwd(HttpServletRequest request, HttpServletResponse response,
            @Valid LoginUser model,
            BindingResult result,
            String newpwd) {
        try {
            if (!result.hasErrors()) {
                UserBean userBean = userService.getUserBeanByMobile(model.getMobile());
                if (userBean != null) {
                    if (BCrypt.checkpw(model.getPassword(), userBean.getPassword())) {
                        UserBean ub = new UserBean();
                        ub.setPassword(BCrypt.hashpw(newpwd, BCrypt.gensalt(10)));
                        ub.setId(userBean.getId());
                        Integer a = userService.updateUserInfo(ub);
                        return new AjaxResponse(true);
                    } else {
                        return new AjaxResponse(false, "旧密码错误");
                    }
                }
            }
        } catch (Exception e) {
            logger.error(e.toString());
        }
        return new AjaxResponse(false, "系统错误");
    }

    /**
     * 发送短信更改手机号码
     *
     * @param request
     * @param response
     * @param mobile
     * @param imageCaptcha
     * @return
     */
    @RequestMapping(value = "updateMobileBySms", method = RequestMethod.POST)
    public @ResponseBody
    AjaxResponse updateMobileBySms(HttpServletRequest request, HttpServletResponse response, String mobile, String newMobile, String checkcode) {
        try {
            String sessionId = request.getSession().getId();
            String redis = redisService.getValueOps().get(sessionId);
            if (redis == null) {
                return new AjaxResponse(false, "手机验证码已失效，请重新发送验证码");
            } else {
                if (!checkcode.equals(redis)) {
                    return new AjaxResponse(false, "手机验证码不正确");
                } else {
                    UserBean userBean = userService.getUserBeanByMobile(mobile);
                    UserBean ub = new UserBean();
                    ub.setId(userBean.getId());
                    ub.setMobile(userBean.getMobile());
                    Integer b = userService.updateUserInfo(ub);
                    return new AjaxResponse(true);
                }
            }
        } catch (Exception e) {
            logger.error(e.toString());
        }
        return new AjaxResponse(false, "系统错误，请稍后重试");
    }

    /**
     * 发送短信
     *
     * @param request
     * @param response
     * @param mobile
     * @param imageCaptcha
     * @return
     */
    @RequestMapping(value = "sendSms", method = RequestMethod.POST)
    public @ResponseBody
    AjaxResponse sendSms(HttpServletRequest request, HttpServletResponse response, String mobile, String imageCaptcha) {
        try {
            String sessionId = request.getSession().getId();
            if (!SessionUtils.validateCaptcha(request, imageCaptcha)) {
                return new AjaxResponse(false, "图片验证码不正确");
            }
            int i = (int) (Math.random() * 1000000 + 100000);
            String messageCode = String.valueOf(i);
            redisService.getValueOps().set(sessionId, messageCode, 2 * 60, TimeUnit.SECONDS);
            logger.info("duan xin is ----------------------" + messageCode);
//            String state = smaClient.sendSMS(mobile, "群商天下验证码:" + messageCode + "");
//            if (state.equals("0")) {
//                return new AjaxResponse(true);
//            } else {
//                return new AjaxResponse(false, "发送失败，请重新发送");
//            }
            return new AjaxResponse(true);
        } catch (Exception e) {
            logger.error(e.toString());
        }
        return new AjaxResponse(false, "系统错误，请稍后重试");
    }

    /**
     * 个人用户中心
     *
     * @param request
     * @param response
     * @return
     */
    @NeedLogin
    @RequestMapping(value = "info", method = RequestMethod.GET)
    public ModelAndView info(HttpServletRequest request, HttpServletResponse response) {
        ModelAndView mv = new ModelAndView("user/info");
        return mv;
    }

    /**
     * 首页
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "index", method = RequestMethod.GET)
    public ModelAndView index(String c) {
        ModelAndView mv = new ModelAndView("index");
        if (StringUtils.isEmpty(c) || c == null) {
            c = "110100";
        }
        List<Area> la = userService.getArea(c);
        List<Category> lc = shopManageService.getCategoryList();
        List<Streets> ls = userService.getHotStreetByCity(c);
        mv.addObject("c", c);
        mv.addObject("la", la);
        mv.addObject("lc", lc);
        mv.addObject("ls", ls);
        return mv;
    }

    /**
     * 商铺搜索页面
     *
     * @param c--城市id
     * @param a--区域id
     * @param p--分类父类id
     * @param s--街道id
     * @param n--分类子类id
     * @return
     */
    @RequestMapping(value = "shoplist", method = RequestMethod.GET)
    public ModelAndView shopList(String c, String a, String p, String s, String n) {
        ModelAndView mv = new ModelAndView("shoplist");
        if (StringUtils.isEmpty(c) || c == null) {
            c = "110100";
        }

        List<Category> lcp = shopManageService.getParentCategory();
        List<Area> la = userService.getArea(c);
        List<Category> lcg = shopManageService.getCategoryList();

        if (p == null || p.equals("0") || StringUtils.isEmpty(p)) {
            p = "0";

        } else {
            List<Category> lc = shopManageService.getCategoryByParent(p);
            mv.addObject("lc", lc);
        }
        if (StringUtils.isEmpty(n) || n == null) {
            n = "0";
        }
        if (StringUtils.isEmpty(a) || a == null || a.equals("0")) {
            a = "0";

        } else {
            List<Streets> ls = userService.getStreetByArea(a);
            mv.addObject("ls", ls);
        }
        if (StringUtils.isEmpty(s) || s == null) {
            s = "0";
        }
        mv.addObject("lcp", lcp);
        mv.addObject("lcg", lcg);
        mv.addObject("la", la);
        mv.addObject("c", c);
        mv.addObject("a", a);
        mv.addObject("p", p);
        mv.addObject("s", s);
        mv.addObject("n", n);
        return mv;
    }

    /**
     * 商品搜索页面
     *
     * @param c--城市id
     * @param a--区域id
     * @param p--分类父类id
     * @param s--街道id
     * @param n--分类子类id
     * @return
     */
    @RequestMapping(value = "comlist", method = RequestMethod.GET)
    public ModelAndView comList(String c, String a, String p, String s, String n) {
        ModelAndView mv = new ModelAndView("comlist");
        if (StringUtils.isEmpty(c) || c == null) {
            c = "110100";
        }

        List<Category> lcp = shopManageService.getParentCategory();
        List<Area> la = userService.getArea(c);
        List<Category> lcg = shopManageService.getCategoryList();

        if (p == null || p.equals("0") || StringUtils.isEmpty(p)) {
            p = "0";

        } else {
            List<Category> lc = shopManageService.getCategoryByParent(p);
            mv.addObject("lc", lc);
        }
        if (StringUtils.isEmpty(n) || n == null) {
            n = "0";
        }
        if (StringUtils.isEmpty(a) || a == null || a.equals("0")) {
            a = "0";

        } else {
            List<Streets> ls = userService.getStreetByArea(a);
            mv.addObject("ls", ls);
        }
        if (StringUtils.isEmpty(s) || s == null) {
            s = "0";
        }
        mv.addObject("lcp", lcp);
        mv.addObject("lcg", lcg);
        mv.addObject("la", la);
        mv.addObject("c", c);
        mv.addObject("a", a);
        mv.addObject("p", p);
        mv.addObject("s", s);
        mv.addObject("n", n);
        return mv;
    }

    @RequestMapping(value = "cominfo", method = RequestMethod.GET)
    public ModelAndView comInfo(ModelMap model) {
        ModelAndView mv = new ModelAndView("commodityinfo");
        logger.info("abc");
        return mv;
    }

    @RequestMapping(value = "shopinfo", method = RequestMethod.GET)
    public ModelAndView shopInfo(ModelMap model) {
        ModelAndView mv = new ModelAndView("shop/shopgouwu");
        return mv;
    }

    @RequestMapping(value = "citylist", method = RequestMethod.GET)
    public ModelAndView cityList(ModelMap model) {
        ModelAndView mv = new ModelAndView("citylist");
        List<City> lc = userService.getCityCapital();
        mv.addObject("lc", lc);
        return mv;
    }

    /**
     * 生成图片验证码
     *
     * @return
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping(value = "captcha", method = RequestMethod.GET, produces = MediaType.IMAGE_PNG_VALUE)
    public byte[] captcha(HttpServletRequest request) throws IOException {
        List<java.awt.Color> textColors = Arrays.asList(new Color(74, 137, 220));
        List<java.awt.Font> textFonts = Arrays.asList(new Font("Courier", Font.PLAIN, 35));
        Captcha captcha = new Captcha.Builder(120, 40)
                .addText(new DefaultTextProducer(),
                        new DefaultWordRenderer(textColors, textFonts))
                .build();

        try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
            ImageIO.write(captcha.getImage(), "png", bos);
            request.getSession().setAttribute(Captcha.NAME, captcha);
            return bos.toByteArray();
        }
    }

    //个人中心---修改资料--页面
    @NeedLogin
    @RequestMapping(value = "updateinfo", method = RequestMethod.GET)
    public ModelAndView updateinfo(HttpServletRequest request, HttpServletResponse response) throws IOException {

        String userId = SessionUtils.getUserId(request);
        if (userId == null || userId.equals("")) {
            response.sendRedirect("/login.do");
        }
        ModelAndView mv = new ModelAndView("user/updateinfo");
        UserBean ubean = userService.getUserBeanById(userId);
        String birthday = ubean.getBirthday();
        if (birthday == null) {
            mv.addObject("year", "2016");
            mv.addObject("month", "2");
            mv.addObject("day", "14");
        } else {
            String[] bir = birthday.split("-");
            mv.addObject("year", bir[0]);
            mv.addObject("month", bir[1]);
            mv.addObject("day", bir[2]);
        }

        mv.addObject("loginName", ubean.getLoginName() == null ? "" : ubean.getLoginName());
        mv.addObject("trueName", ubean.getTrueName() == null ? "" : ubean.getTrueName());
        mv.addObject("sex", ubean.getSex());
        mv.addObject("id", userId);
        return mv;
    }

    //个人中心---修改资料--更改
    @NeedLogin
    @RequestMapping(value = "updateinfo", method = RequestMethod.POST)
    public @ResponseBody
    String updateInfo(HttpServletRequest request,
            HttpServletResponse response,
            @RequestParam("userId") String userId,
            @RequestParam("loginName") String loginName,
            @RequestParam("trueName") String trueName,
            @RequestParam("birthday") String birthday,
            @RequestParam("sex") int sex
    ) {
        UserBean userBean = new UserBean();
        userBean.setId(userId);
        userBean.setBirthday(birthday);
        userBean.setLoginName(loginName);
        userBean.setTrueName(trueName);
        userBean.setSex(sex);
        try {
            Integer n = userService.updateUserInfo(userBean);
            if (n > 0) {
                return "success";
            } else {
                return "false";
            }
        } catch (Exception e) {
            logger.error("update user info failed,reason is {},userId is {}", e.toString(), userId);
            return "false";
        }

    }

    //个人中心---修改手机
    @NeedLogin
    @RequestMapping(value = "changetel", method = RequestMethod.GET)
    public ModelAndView changetel(HttpServletRequest request, HttpServletResponse response) {
        List<Commodity> clist = userService.getRecommendList();
        ModelAndView mv = new ModelAndView("user/changetel");
        for (Commodity c : clist) {
            c.setDescrip(c.getDescrip().substring(0, 16) + "...");
        }
        mv.addObject("clist", clist);
        return mv;
    }

    //个人中心---修改密码
    @NeedLogin
    @RequestMapping(value = "changepas", method = RequestMethod.GET)
    public ModelAndView changepas(HttpServletRequest request, HttpServletResponse response) {
        ModelAndView mv = new ModelAndView("user/changepas");
        return mv;
    }

    //个人中心---修改地址页面
    @NeedLogin
    @RequestMapping(value = "changeadd", method = RequestMethod.GET)
    public ModelAndView changeadd(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String userId = SessionUtils.getUserId(request);
        if (userId == null || userId.equals("")) {
            response.sendRedirect("/login.do");
        }
        ModelAndView mv = new ModelAndView("user/changeadd");
        try {
            List<UserAddress> udlist = userService.getAddressListByUserId(userId);
            Integer num = userService.getAddressNumberByUserId(userId);
            if (num > 0) {
                mv.addObject("udlist", udlist);
            }
        } catch (Exception e) {
            logger.error(e.toString());
        }
        mv.addObject("id", userId);
        return mv;
    }

    //个人中心---修改地址--更改/添加
    @NeedLogin
    @RequestMapping(value = "updateUserAddress", method = RequestMethod.POST)
    public @ResponseBody
    String updateUserAddress(HttpServletRequest request,
            HttpServletResponse response,
            @RequestParam("id") String id,
            @RequestParam("userId") String userId,
            @RequestParam("name") String name,
            @RequestParam("mobile") String mobile,
            @RequestParam("address") String address,
            @RequestParam("zipCode") String zipCode,
            @RequestParam("p") int p,
            @RequestParam("c") int c,
            @RequestParam("a") int a
    ) {
        UserAddress ua = new UserAddress();
        ua.setAddress(address);
        ua.setArea(a);
        ua.setCity(c);
        ua.setMobile(mobile);
        ua.setName(name);
        ua.setProvince(p);
        ua.setUserId(userId);
        ua.setZipCode(zipCode);
        try {
            if (id == null || id.equals("")) {
                id = UUID.randomUUID().toString();
                ua.setId(id);
                Integer an = userService.addAddressByUserId(ua);
                if (an > 0) {
                    return "addsuccess";
                } else {
                    return "addfalse";
                }
            } else {
                ua.setId(id);
                Integer n = userService.updateAddressInfoById(ua);
                if (n > 0) {
                    return "success";
                } else {
                    return "false";
                }
            }
        } catch (Exception e) {
            logger.error("update/add user address failed,reason is {},userId is {}", e.toString(), userId);
            return "allfalse";
        }

    }

    //个人中心---修改地址--更改地址状态
    @NeedLogin
    @RequestMapping(value = "updateAddressState", method = RequestMethod.POST)
    public @ResponseBody
    String updateAddressState(HttpServletRequest request,
            HttpServletResponse response,
            @RequestParam("id") String id,
            @RequestParam("userId") String userId
    ) {

        try {
            Integer alln = userService.updateAllAddressStateByUserId(userId);
            if (alln > 0) {
                Integer an = userService.updateAddressStateById(id, 1);
                if (an > 0) {
                    return "success";
                } else {
                    return "false";
                }
            } else {
                return "false";
            }

        } catch (Exception e) {
            logger.error("update user address state failed,reason is {},userId is {}", e.toString(), userId);
            return "false";
        }

    }

    //个人中心---修改地址--删除地址
    @NeedLogin
    @RequestMapping(value = "deleteAddress", method = RequestMethod.POST)
    public @ResponseBody
    String deleteAddress(HttpServletRequest request,
            HttpServletResponse response,
            @RequestParam("id") String id
    ) {
        try {
            UserAddress ua = userService.getAddressById(id);
            if (ua.getIsDefault() == 1) {
                return "dfalse";
            }
            Integer an = userService.deleteAddressById(id);
            if (an > 0) {
                return "success";
            } else {
                return "false";
            }

        } catch (Exception e) {
            logger.error("delete user address failed,reason is {},id is {}", e.toString(), id);
            return "false";
        }

    }

    /**
     * 个人中心--获取单个地址
     *
     * @param request
     * @param response
     * @param id
     * @return
     * @throws IOException
     */
    @NeedLogin
    @RequestMapping(value = "getAddressById", method = RequestMethod.POST, produces = javax.ws.rs.core.MediaType.APPLICATION_JSON)
    @ResponseBody
    public UserAddress getAddressById(HttpServletRequest request,
            HttpServletResponse response,
            @RequestParam("id") String id) throws IOException {
        UserAddress ua = userService.getAddressById(id);
        return ua;
    }

    //个人中心---交易关闭
    @NeedLogin
    @RequestMapping(value = "shuttran", method = RequestMethod.GET)
    public ModelAndView shuttran(HttpServletRequest request, HttpServletResponse response, Integer p) {
        ModelAndView mv = new ModelAndView("user/shuttran");
        String userId = SessionUtils.getUserId(request);
        int length = 4;
        int pagecount = 0;//页数
        if (p == null) {
            p = 1;
        }
        int start = (p - 1) * length;
        int count = 20;
        if (count % length == 0) {
            pagecount = count / length;
        } else {
            pagecount = (count / length + 1);
        }
        List<OrderDto> lod = userOrderService.getOrderListByType(userId, String.valueOf(OrderState.SHUTDOWN), p, length);
        mv.addObject("ps", length);
        mv.addObject("p", p);
        mv.addObject("count", count);
        mv.addObject("pagecount", pagecount);
        mv.addObject("lod", lod);
        return mv;
    }

    //个人中心---订单---进行中
    @NeedLogin
    @RequestMapping(value = "traning", method = RequestMethod.GET)
    public ModelAndView traning(HttpServletRequest request, HttpServletResponse response, Integer p) {
        ModelAndView mv = new ModelAndView("user/traning");
        String userId = SessionUtils.getUserId(request);
        int length = 4;
        int pagecount = 0;//页数
        if (p == null) {
            p = 1;
        }
        int start = (p - 1) * length;
        int count = userOrderService.getCountByOrderType(userId, String.valueOf(OrderState.TRANING));
        if (count % length == 0) {
            pagecount = count / length;
        } else {
            pagecount = (count / length + 1);
        }
        List<OrderDto> lod = userOrderService.getOrderListByType(userId, String.valueOf(OrderState.TRANING), start, length);

        mv.addObject("ps", length);
        mv.addObject("p", p);
        mv.addObject("count", count);
        mv.addObject("pagecount", pagecount);
        mv.addObject("today", new Date());
        mv.addObject("lod", lod);
        return mv;
    }

    //个人中心---交易已完成
    @NeedLogin
    @RequestMapping(value = "traned", method = RequestMethod.GET)
    public ModelAndView traned(HttpServletRequest request, HttpServletResponse response, Integer p) {
        ModelAndView mv = new ModelAndView("user/traned");
        String userId = SessionUtils.getUserId(request);
        int length = 4;
        int pagecount = 0;//页数
        if (p == null) {
            p = 1;
        }
        int start = (p - 1) * length;
        int count = 20;
        if (count % length == 0) {
            pagecount = count / length;
        } else {
            pagecount = (count / length + 1);
        }
        List<OrderDto> lod = userOrderService.getOrderListByType(userId, String.valueOf(OrderState.COMPLETED), p, length);
        mv.addObject("ps", length);
        mv.addObject("p", p);
        mv.addObject("count", count);
        mv.addObject("pagecount", pagecount);
        mv.addObject("lod", lod);
        return mv;
    }

    //个人中心---购物车
    @NeedLogin
    @RequestMapping(value = "cart", method = RequestMethod.GET)
    public ModelAndView usershopcar(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String userId = SessionUtils.getUserId(request);
        if (userId == null || userId.equals("")) {
            response.sendRedirect("/login.do");
        }
        List<UserCart> uclist = userOrderService.getCartListByUserId(userId);
        ModelAndView mv = new ModelAndView("user/cart");
        mv.addObject("uclist", uclist);
        return mv;
    }

    //添加购物车
    @NeedLogin
    @RequestMapping(value = "addCart", method = RequestMethod.POST)
    public @ResponseBody
    String addCart(HttpServletRequest request,
            HttpServletResponse response,
            @RequestParam("ids") String ids
    ) throws IOException {
        String userId = SessionUtils.getUserId(request);
        if (userId == null || userId.equals("")) {
            response.sendRedirect("/login.do");
        }
        try {
            String strEnd = ids.substring(ids.length() - 1, ids.length());
            if (strEnd.equals(",")) {
                ids = ids.substring(0, ids.length() - 1);
            }
            String[] cartArry = ids.split(",");
            Integer a = userOrderService.deleteCartById(cartArry, userId);
            if (a > 0) {
                return "success";
            } else {
                return "false";
            }
        } catch (Exception e) {
            logger.error("delete user address failed,reason is {},id is {}", e.toString(), ids);
            return "false";
        }
    }

    //更改购物车数量
    @NeedLogin
    @RequestMapping(value = "updateCartNum", method = RequestMethod.POST)
    public @ResponseBody
    String updateCartNum(HttpServletRequest request,
            HttpServletResponse response,
            @RequestParam("cart") String cart
    ) throws IOException {
        String userId = SessionUtils.getUserId(request);
        if (userId == null || userId.equals("")) {
            response.sendRedirect("/login.do");
        }
        try {
            JSONObject jsonObject = JSONObject.fromObject(cart);
            for (Iterator iter = jsonObject.keys(); iter.hasNext();) {
                String key = (String) iter.next();
                String num = jsonObject.get(key).toString();
                Integer a = userOrderService.updateCartById(Integer.parseInt(num), key);
            }
            return "success";

        } catch (Exception e) {
            logger.error("delete user address failed,reason is {}", e.toString());
            return "false";
        }
    }

    //删除购物车---单个，多个删除
    @NeedLogin
    @RequestMapping(value = "deleteCart", method = RequestMethod.POST)
    public @ResponseBody
    String deleteCart(HttpServletRequest request,
            HttpServletResponse response,
            @RequestParam("ids") String ids
    ) throws IOException {
        String userId = SessionUtils.getUserId(request);
        if (userId == null || userId.equals("")) {
            response.sendRedirect("/login.do");
        }
        try {
            String strEnd = ids.substring(ids.length() - 1, ids.length());
            if (strEnd.equals(",")) {
                ids = ids.substring(0, ids.length() - 1);
            }
            String[] cartArry = ids.split(",");
            Integer a = userOrderService.deleteCartById(cartArry, userId);
            if (a > 0) {
                return "success";
            } else {
                return "false";
            }
        } catch (Exception e) {
            logger.error("delete user address failed,reason is {},id is {}", e.toString(), ids);
            return "false";
        }
    }

    //个人中心---确认订单
    @NeedLogin
    @RequestMapping(value = "confirmorder", method = RequestMethod.GET)
    public ModelAndView cfirmorder(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String userId = SessionUtils.getUserId(request);
        if (userId == null || userId.equals("")) {
            response.sendRedirect("/login.do");
        }
        ModelAndView mv = new ModelAndView("user/confirmorder");
        List<UserCart> uclist = userOrderService.getCartListByUserId(userId);
        List<UserAddress> udlist = userService.getAddressListByUserId(userId);
        mv.addObject("uclist", uclist);
        mv.addObject("udlist", udlist);
        return mv;
    }
    //从购物车保存订单

    @NeedLogin
    @RequestMapping(value = "addOrderByCart", method = RequestMethod.POST)
    public @ResponseBody
    String addOrderByCart(HttpServletRequest request,
            HttpServletResponse response,
            @RequestParam("str") String str
    ) throws IOException {
        String userId = SessionUtils.getUserId(request);
        if (userId == null || userId.equals("")) {
            response.sendRedirect("/login.do");
        }
        String rstr = "";
        Order order = new Order();
        try {
            JSONArray array = JSONArray.fromObject(str);
            Order[] obj = new Order[array.size()];
            for (int i = 0; i < array.size(); i++) {
                JSONObject jsonObject = array.getJSONObject(i);
                obj[i] = (Order) JSONObject.toBean(jsonObject, order.getClass());
                obj[i].setUserId(userId);
                String id = UUID.randomUUID().toString();
                obj[i].setId(id);
                obj[i].setOrderState(String.valueOf(OrderState.TRANING));
                Integer a = userOrderService.addOrderByUserId(obj[i]);
                if (a > 0) {
                    String[] cartArry = new String[1];
                    cartArry[0] = obj[i].getCartId();
                    Integer c = userOrderService.deleteCartById(cartArry, userId);
                    rstr = "success";
                } else {
                    rstr = "faile";
                }
            }
            return rstr;

        } catch (Exception e) {
            logger.error("delete user address failed,reason is {}", e.toString());
            return "faile";
        }
    }

    //个人中心--获取省市区
    @RequestMapping(value = "userInfo/getProvinceList", method = RequestMethod.GET, produces = javax.ws.rs.core.MediaType.APPLICATION_JSON)
    @ResponseBody
    public List<Province> getProvinceList() throws IOException {
        List<Province> plist = userService.getProvince();
        return plist;
    }

    @RequestMapping(value = "userInfo/getCityList", method = RequestMethod.GET, produces = javax.ws.rs.core.MediaType.APPLICATION_JSON)
    @ResponseBody
    public List<City> getCityList(String id) throws IOException {
        List<City> clist = userService.getCity(id);
        return clist;
    }

    @RequestMapping(value = "userInfo/getAreaList", method = RequestMethod.GET, produces = javax.ws.rs.core.MediaType.APPLICATION_JSON)
    @ResponseBody
    public List<Area> getAreaList(String id) throws IOException {
        List<Area> alist = userService.getArea(id);
        return alist;
    }

    //个人中心---收藏的店铺
    @NeedLogin
    @RequestMapping(value = "collecshop", method = RequestMethod.GET)
    public ModelAndView collecshop(HttpServletRequest request, HttpServletResponse response) {
        String userId = SessionUtils.getUserId(request);
        List<Shop> ls = userService.getColShopById(userId);
        ModelAndView mv = new ModelAndView("user/collecshop");
        mv.addObject("ls", ls);
        return mv;
    }

    //个人中心---收藏的商品
    @NeedLogin
    @RequestMapping(value = "colleccom", method = RequestMethod.GET)
    public ModelAndView colleccom(HttpServletRequest request, HttpServletResponse response) {
        String userId = SessionUtils.getUserId(request);
        List<Commodity> lc = userService.getColComById(userId);
        ModelAndView mv = new ModelAndView("user/colleccom");
        mv.addObject("lc", lc);
        return mv;
    }

    //取消收藏---单个，多个取消
    @NeedLogin
    @RequestMapping(value = "deleteUserStore", method = RequestMethod.POST)
    public @ResponseBody
    AjaxResponse deleteUserStore(HttpServletRequest request,
            HttpServletResponse response,
            @RequestParam("ids") String ids
    ) throws IOException {
        String userId = SessionUtils.getUserId(request);
        try {
            String strEnd = ids.substring(ids.length() - 1, ids.length());
            if (strEnd.equals(",")) {
                ids = ids.substring(0, ids.length() - 1);
            }
            String[] storeArry = ids.split(",");
            Integer a = userService.deleteStoreById(userId, storeArry);
            if (a > 0) {
                return new AjaxResponse(true);
            } else {
                return new AjaxResponse(false, "取消收藏失败");
            }
        } catch (Exception e) {
            logger.error("delete user address failed,reason is {},id is {}", e.toString(), ids);
            return new AjaxResponse(false, "系统错误，取消收藏失败");
        }
    }

    @NeedLogin
    @RequestMapping(value = "addUserStore", method = RequestMethod.POST)
    public @ResponseBody
    AjaxResponse addUserStore(HttpServletRequest request,
            HttpServletResponse response,
            @RequestParam("sid") String sid,
            @RequestParam("t") int t
    ) throws IOException {
        String userId = SessionUtils.getUserId(request);
        UserStore us = new UserStore();
        String id = UUID.randomUUID().toString();
        us.setId(id);
        us.setUserId(userId);
        try {
            if (t == 1) {
                us.setCommodityId(sid);
            }
            if (t == 2) {
                us.setShopId(sid);
            }
            Integer a = userService.addUserStore(us);
            if (a > 0) {
                return new AjaxResponse(true);
            } else {
                return new AjaxResponse(false, "添加收藏失败");
            }

        } catch (Exception e) {
            logger.error("delete user address failed,reason is {}", e.toString());
            return new AjaxResponse(false, "系统错误，添加收藏失败");
        }
    }

    //关于我们
    @RequestMapping(value = "aboutus", method = RequestMethod.GET)
    public ModelAndView aboutus(HttpServletRequest request, HttpServletResponse response) {
        String userId = SessionUtils.getUserId(request);
        List<Category> lcg = shopManageService.getCategoryList();
        ModelAndView mv = new ModelAndView("aboutus");
        mv.addObject("lcg", lcg);
        return mv;
    }

    //商务合作
    @RequestMapping(value = "cooperation", method = RequestMethod.GET)
    public ModelAndView cooperation(HttpServletRequest request, HttpServletResponse response) {
        ModelAndView mv = new ModelAndView("cooperation");
        return mv;
    }

    @RequestMapping(value = "addCooperation", method = RequestMethod.POST)
    public @ResponseBody
    AjaxResponse addCooperation(HttpServletRequest request, HttpServletResponse response, String mobile,
            String imageCaptcha, String intention) {
        try {
            if (!SessionUtils.validateCaptcha(request, imageCaptcha)) {
                return new AjaxResponse(false, "图片验证码不正确");
            }
            String id = UUID.randomUUID().toString();
            if (StringUtils.isEmpty(mobile)) {
                return new AjaxResponse(false, "手机号码不可为空");
            }
            Integer b = userService.getCountByMobile(mobile);
            if (b == 0) {
                Cooperation c = new Cooperation();
                c.setId(id);
                c.setIntention(intention);
                c.setMobile(mobile);
                int a = userService.addUserCooperation(c);
                if (a > 0) {
                    return new AjaxResponse(true);
                } else {
                    return new AjaxResponse(false, "保存失败，请重新提交");
                }
            } else {
                return new AjaxResponse(false, "保存失败，该电话号码已存在");
            }

        } catch (Exception e) {
            logger.error(e.toString());
        }
        return new AjaxResponse(false, "系统错误");
    }
}
